package com.jxpanda.spring.module.wechat.config;

import com.jxpanda.spring.module.wechat.component.message.handler.WechatReceivedXmlMessageHandler;
import com.jxpanda.spring.module.wechat.component.message.handler.WechatReceivedXmlMessageHandlers;
import com.jxpanda.spring.module.wechat.config.properties.WechatConfigProperties;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(WechatConfigProperties.class)
public class WechatModuleAutoConfigure {

    private final WechatConfigProperties wechatConfigProperties;
    private final ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        WechatConfigProperties.init(wechatConfigProperties);
    }

    @Bean
    @SuppressWarnings("unchecked")
    public WechatReceivedXmlMessageHandlers wechatMessageHandlers() {
        WechatReceivedXmlMessageHandlers wechatReceivedXmlMessageHandlers = new WechatReceivedXmlMessageHandlers();
        applicationContext.getBeansOfType(WechatReceivedXmlMessageHandler.class)
                .forEach((beanName, handler) -> {
                    wechatReceivedXmlMessageHandlers.addHandler(handler.msgType(), handler);
                });
        return wechatReceivedXmlMessageHandlers;
    }

}